Jump to content

User:Awesome Aasim/redirectcreator.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
if (!RedirCreator && mw.config.get("wgPageName").toLowerCase().startsWith("Special:Search".toLowerCase())) {
    var RedirCreator = {}
    $(document).ready(function () {
        if (!$(".mw-search-exists").text()) {
            var page = $("#ooui-php-1").val()
            $(".mw-search-result-heading").each(function (i) {
                $(this).append('<span class="redirectcreator">(<a id="redirectcreator-' + i + '" href="javascript:void(0)">redirect</a>)</span>')
                $("#redirectcreator-" + i).click(function (e) {
                    e.preventDefault()
                    var target = $(this).parent().parent().find("a").eq(0).text();
                    var section = $(this).parent().parent().find("a").eq(1) ? $(this).parent().parent().find("a").eq(1).find("span").text() : null;
                    RedirCreator.run = confirm("Create redirect from \"" + page + "\" to \"" + target + (section ? "#" + section: "") + "\"?")
                    if (RedirCreator.run) {
                        $.get(mw.config.get("wgScriptPath") + "/api.php", {
                            action: "query",
                            format: "json",
                            meta: "tokens",
                            type: "csrf"
                        }).done(function (result) {
                            if (result.error) {
                                alert(result.error.info)
                            } else {
                                $.post(mw.config.get("wgScriptPath") + "/api.php", {
                                    action: "edit",
                                    format: "json",
                                    createonly: "1",
                                    title: page,
                                    text: "#REDIRECT [[" + target + (section ? "#" + section: "") + "]]",
                                    summary: "Created redirect from [[" + page + "]] to [[" + target + (section ? "#" + section: "") + "]] using [[User:Awesome Aasim/redirectcreator|redirect creator]]",
                                    token: result.query.tokens.csrftoken
                                }).done(function (result) {
                                    if (result.error) {
                                        alert(result.error.info)
                                    } else {
                                        mw.notify("Redirect successfully created.")
                                        $(".redirectcreator").remove();
                                    }
                                }).fail(function () {
                                    location.reload()
                                })
                            }
                        }).fail(function () {
                            location.reload()
                        })
                    }
                })
            })
        }
    })
} else if (!RedirCreator && mw.config.get("wgPageName").toLowerCase() == "Special:BlankPage/RedirectCreator".toLowerCase()) {
    var RedirCreator = {}
    $(document).ready(function () {
    	$("#firstHeading").text("Redirect creator")
    	$("title").text("Redirect creator - " + mw.config.get("wgSiteName"))
        $("#mw-content-text").html("<p>The redirect creator can create multiple redirects. Please be aware of your wiki's policy on redirects and automated tools and do not use this tool excessively. Once you click \"Start\", you will only get one chance to abort the task.</p>")
        $("#mw-content-text").append("<form id=\"redirectcreator-form\"></form>")
        $("#redirectcreator-form").append('<h2>Rate limit</h2><p>Make one edit every <input type="number" id="redirectcreator-rate" value="8" required="true" min="0"> second(s).</p>')
        $("#redirectcreator-form").append('<h2>Redirects</h2>')
        $("#redirectcreator-form").append('<p>To create multiple redirects to the same target, enter the target in the first "target" field and all the pages to redirect to that target in the "pages" column.  Any blank optional fields will be auto-filled with the first redirect target.</p>')
        $("#redirectcreator-form").append('<table id="redirectcreator-table"><tr><th style="align:center">Redirect page</th><th style="align:center">Redirect target</th><th>(<a id="redirectcreator-addanother">+</a>)</th></tr></table>')
        $("#redirectcreator-table").append('<tr id="redirectcreator-row1"><td><input id="redirectcreator-page1" placeholder="Please enter redirect title here" required="true"></td><td><input id="redirectcreator-target1" placeholder="Please enter redirect target here (sections supported)" required="true"></td><td></td></tr>')
        $('#redirectcreator-page1').keypress(function (e) {
            switch (e.which || e.keyCode) {
                case 35: e.preventDefault()
                    break
                case 60: e.preventDefault()
                    break
                case 62: e.preventDefault()
                    break
                case 91: e.preventDefault()
                    break
                case 93: e.preventDefault()
                    break
                case 123: e.preventDefault()
                    break
                case 125: e.preventDefault()
                    break
                case 124: e.preventDefault()
                    break
            }
        })
        $('#redirectcreator-target1').keypress(function (e) {
            switch (e.which || e.keyCode) {
                case 60: e.preventDefault()
                    break
                case 62: e.preventDefault()
                    break
                case 91: e.preventDefault()
                    break
                case 93: e.preventDefault()
                    break
                case 123: e.preventDefault()
                    break
                case 125: e.preventDefault()
                    break
                case 124: e.preventDefault()
                    break
            }
        })
        RedirCreator.i = 2
        RedirCreator.isEmpty = function (str) {
            return str.replace(/\s/g, '').length == 0;
        }
        RedirCreator.addanother = function () {
            $("#redirectcreator-form").find("input").keydown(function (e) {
                if (RedirCreator.isEmpty($(this).val()) && $(this).prop('required')) {
                	$(this).css("background-color", "yellow");
                    exit = true
                } else {
                	$(this).css("background-color", "white");
                }
            })
            $("#redirectcreator-table").append('<tr id="redirectcreator-row' + RedirCreator.i + '"><td><input id="redirectcreator-page' + RedirCreator.i + '" placeholder="Please enter redirect title here" required="true"></td><td><input id="redirectcreator-target' + RedirCreator.i + '" placeholder="Please enter redirect target here (sections supported)"></td><td>(<a id="redirectcreator-remove' + RedirCreator.i + '" data-redirect-number="' + RedirCreator.i + '">-</a>)</td></tr>')
            $("#redirectcreator-remove" + RedirCreator.i).click(function (e) {
                e.preventDefault()
                var removeid = $(this).data("redirect-number")
                $("#redirectcreator-row" + removeid).remove()
            })
            $('#redirectcreator-page' + RedirCreator.i).keypress(function (e) {
                switch (e.which || e.keyCode) {
                    case 35: e.preventDefault()
                        break
                    case 60: e.preventDefault()
                        break
                    case 62: e.preventDefault()
                        break
                    case 91: e.preventDefault()
                        break
                    case 93: e.preventDefault()
                        break
                    case 123: e.preventDefault()
                        break
                    case 125: e.preventDefault()
                        break
                    case 124: e.preventDefault()
                        break
                }
            })
            $('#redirectcreator-target' + RedirCreator.i).keypress(function (e) {
                switch (e.which || e.keyCode) {
                    case 60: e.preventDefault()
                        break
                    case 62: e.preventDefault()
                        break
                    case 91: e.preventDefault()
                        break
                    case 93: e.preventDefault()
                        break
                    case 123: e.preventDefault()
                        break
                    case 125: e.preventDefault()
                        break
                    case 124: e.preventDefault()
                        break
                }
            })
            RedirCreator.i++;
        }
        $("#redirectcreator-addanother").click(RedirCreator.addanother);
        $("#redirectcreator-form").append('<h2>Start</h2><p>Once you click start, you will not be able to reconfigure these settings, but you can abort at any time by closing out this window.</p><button type="submit" id="redirectcreator-start" onclick="RedirCreator.start()">Start</button><div id="redirectcreator-output"></div>')
        RedirCreator.start = function () {
            $("#redirectcreator-form").find("input").prop("disabled", true)
            $("#redirectcreator-form").find("button").prop("disabled", true)
            var exit = false
            // check that all required fields are filled out correctly. If they are not, then immediately stop.
            $("#redirectcreator-form").find("input").each(function (i) {
                if (RedirCreator.isEmpty($(this).val()) && $(this).prop('required')) {
                	$(this).css("background-color", "yellow");
                    exit = true
                } else {
                	$(this).css("background-color", "white");
                }
            })
            if (exit) {
                $("#redirectcreator-form").find("input").prop("disabled", false)
                $("#redirectcreator-form").find("button").prop("disabled", false)
                return
            }
            // autofill non-required fields that are empty with the required target, exit, then wait until it is run again
            RedirCreator.singletarget = $("#redirectcreator-table").find("tr").eq(1).find("input").eq(1).val()
            $("#redirectcreator-table").find("tr").each(function (i) {
                if (i == 0) {
                    return
                }
                if (RedirCreator.isEmpty($(this).find("input").eq(1).val())) {
                    $(this).find("input").eq(1).val(RedirCreator.singletarget)
                    exit = true
                }
            })
            if (exit) {
                alert("All blank nonrequired fields have been autofilled with the first required redirect target. Please check that everything has been done correctly.")
                $("#redirectcreator-form").find("input").prop("disabled", false)
                $("#redirectcreator-form").find("button").prop("disabled", false)
                return
            }
            if (!confirm("Are you sure you want to start?")) {
                $("#redirectcreator-form").find("input").prop("disabled", false)
                $("#redirectcreator-form").find("button").prop("disabled", false)
                return
            }

            if (!confirm("LAST CHANCE TO BACK DOWN.  ANY DISRUPTION YOU CAUSE WITH THIS MAY RESULT IN YOU BEING BLOCKED FROM EDITING.")) {
                $("#redirectcreator-form").find("input").prop("disabled", false)
                $("#redirectcreator-form").find("button").prop("disabled", false)
                return
            }

            // time to start
            RedirCreator.redirpairs = []
            RedirCreator.delay = $("#redirectcreator-rate").val()
            $("#redirectcreator-table").find("tr").each(function (i) {
                if (i == 0) {
                    return
                }
                RedirCreator.redirpairs.push([$(this).find("input").eq(0).val(), $(this).find("input").eq(1).val()])
            })
            var output = function (text) {
                $("#redirectcreator-output").append(text)
            }
            RedirCreator.j = -1
            var next = function () {
                RedirCreator.j += 1
                if (RedirCreator.j < RedirCreator.redirpairs.length) {
                    RedirCreator.createRedirect(RedirCreator.redirpairs[RedirCreator.j][0], RedirCreator.redirpairs[RedirCreator.j][1])
                } else {
                    output("<span style=\"color:green\">Finished.</span>");
                }
            }
            RedirCreator.createRedirect = function (page, target) {
                output("> Creating redirect between " + page + " and " + target + "...");
                try {
                    $.get(mw.config.get("wgScriptPath") + "/api.php", {
                        action: "parse",
                        prop: "wikitext",
                        format: "json",
                        page: target
                    }).done(function (result) {
                        if (result.error) {
                            output("<span style=\"color:orange\">Target page does not exist. Skipping...</span><br>");
                            window.setTimeout(next, RedirCreator.delay * 1000);
                        } else {
                            $.get(mw.config.get("wgScriptPath") + "/api.php", {
                                action: "query",
                                format: "json",
                                meta: "tokens",
                                type: "csrf"
                            }).done(function (result) {
                                if (result.error) {
                                    output("<span style=\"color:orange\">Error: " + result.error.info + " Skipping...</span><br>");
                                    window.setTimeout(next, RedirCreator.delay * 1000);
                                } else {
                                    $.post(mw.config.get("wgScriptPath") + "/api.php", {
                                        action: "edit",
                                        format: "json",
                                        createonly: "1",
                                        title: page,
                                        text: "#REDIRECT [[" + target + "]]",
                                        summary: "Created redirect from [[" + page + "]] to [[" + target + "]] using [[User:Awesome Aasim/redirectcreator|redirect creator]]",
                                        token: result.query.tokens.csrftoken
                                    }).done(function (result) {
                                        if (result.error) {
                                            output("<span style=\"color:orange\">Error: " + result.error.info + " Skipping...</span><br>");
                                            window.setTimeout(next, RedirCreator.delay * 1000);
                                        } else {
                                            output("<span style=\"color:green\">Done</span><br>");
                                            window.setTimeout(next, RedirCreator.delay * 1000);
                                        }
                                    }).fail(function () {
                                        throw "Fail"
                                    })
                                }
                            }).fail(function () {
                                throw "Fail"
                            })
                        }
                    }).fail(function () {
                        throw "Fail"
                    })
                } catch (Error) {
                    alert("Lost connection. Aborting.")
                    output("<br><span style=\"color:red\">Failed.</span>");
                }
            }
            next()
        }
    })
}